package com.petter.rabbitmq.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author : GD
 * @date :2022/3/10 : 22:11
 */
public class RoutingProducer {

    public final static String QUEUE_NAME = "routingQueue";
    public final static String QUEUE_NAME2 = "routingQueue2";
    public final static String EXCHANGE_NAME = "routing exchange";

    public static void main(String[] args) throws Exception {

        // 1. 获取链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        // 此处用户需要有虚拟机节点权限，否则会链接报错 ,在admin -> 用户 -> set permission
//        connection error; protocol method: #method<connection.close>(reply-code=530, reply-text=NOT_ALLOWED - access to vhost '/' refused for user 'admin', class-id=10, method-id=40)
        factory.setUsername("admin");
        factory.setPassword("admin");
        // 2. 通过工厂获取连接
        Connection connection = factory.newConnection();
        // 3. 通过连接获取channel
        Channel channel = connection.createChannel();
        // 4. 声明一个交换队列 ，类型为fanout // direct 可以路由，但是不支持模糊匹配，必须是精确匹配
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        // 5. 声明队列，及交换机绑定队列
        channel.queueDeclare(RoutingProducer.QUEUE_NAME,true,false,false,null);
        channel.queueBind(RoutingProducer.QUEUE_NAME, RoutingProducer.EXCHANGE_NAME,"mail");
        channel.queueDeclare(RoutingProducer.QUEUE_NAME2,true,false,false,null);
        channel.queueBind(RoutingProducer.QUEUE_NAME2, RoutingProducer.EXCHANGE_NAME,"log");
        // 5. 发布对应的消息到消息队列
        String message = "Hello World!";
        channel.basicPublish(EXCHANGE_NAME, "mail", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        // 此数据是无法推送到队列中的
        channel.basicPublish(EXCHANGE_NAME, "com.log.petter", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

        channel.basicPublish(EXCHANGE_NAME, "log", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
    }

}
